package validator

import (
	"fmt"
	"reflect"
	"regexp"
)

type StringRegex struct {
	reg   *regexp.Regexp
	exp   string
	match bool
}

func NewStringRegex(exp string, match bool) *StringRegex {
	return &StringRegex{
		reg:   regexp.MustCompile(exp),
		exp:   exp,
		match: match,
	}
}

func (r *StringRegex) String() string {
	if r.match {
		return fmt.Sprintf("[$%s", r.exp)
	}
	return fmt.Sprintf("($%s", r.exp)
}

func (r *StringRegex) IsValidate(field string, data reflect.Value) error {
	var val = data.Interface()
	str, ok := val.(string)
	if !ok {
		return NewErrType(field, data.Type().Name(), "string")
	}
	found := r.reg.FindString(str)
	if found != str {
		// 未匹配
		if r.match {
			return fmt.Errorf("%s's value do not match with regular expression %s", field, r.exp)
		}
	} else {
		// 匹配
		if !r.match {
			return fmt.Errorf("%s's value must not match with regular expression %s", field, r.exp)
		}
	}
	return nil
}
